local market_buy, limit_buy, market_sell, limit_sell = 0, 0, 0, 0
local market_buy_key = "etf:orderbook:" .. ARGV[1] .. ":BUY:MARKET"
local limit_buy_key = "etf:orderbook:" .. ARGV[1] .. ":BUY:LIMIT"
local market_sell_key = "etf:orderbook:" .. ARGV[1] .. ":SELL:MARKET"
local limit_sell_key = "etf:orderbook:" .. ARGV[1] .. ":SELL:LIMIT"
local function getBuy()
    local result = redis.call("lindex", market_buy_key, -1)
    if (result ~= false) then
        market_buy = result
    else
        local result = redis.call("zrange", limit_buy_key, -1, -1)
        if next(result) ~= nil then
            local data = cjson.decode(result[1])
            local temp = {}
            for i, v in ipairs(data) do
                table.insert(temp, v[1])
            end
            table.sort(temp)
            limit_buy = temp[1]
        end
    end
end
local function getLimitSell()
    local result = redis.call("zrange", limit_sell_key, 0, 0)
    if (next(result) ~= nil) then
        local data = cjson.decode(result[1])
        local temp = {}
        for i, v in ipairs(data) do
            table.insert(temp, v[1])
        end
        table.sort(temp)
        limit_sell = temp[1]
    end
end
local function getSell()
    if (market_buy ~= 0) then
        getLimitSell()
    else
        local result = redis.call("lindex", market_sell_key, -1)
        if (result ~= false) then
            market_sell = result
        else
            getLimitSell()
        end
    end
end
getBuy()
getSell()
return { market_buy, limit_buy, market_sell, limit_sell }